
#coding:utf-8
# __author__ = 'admin'
# __all__ = ["BaseHandler", "extract_param", "sendrequest"]

from socket import socket, AF_INET, SOCK_STREAM
import gvars


# class BaseHandler:
#     """ The base handler class
#
#     All module handler class is extended from BaseHanlder,
#     and the subclass need overried handle(reqdict) function.
#
#     """
#     def __init__(self):
#         self.echo = None
#
#     def handle(self, reqdict):
#         pass
#
#     def handle_agent_side(self, reqdict, request_socket):
#         socket_in = request_socket.makefile('rt')
#         socket_out = request_socket.makefile('wt')
#         while True:
#             line = socket_in.readline()
#             if line.startswith(gvars.EOFSTR):
#                 break
#             if not line.isspace():
#                 kv = line.strip().split('=', 1)
#                 if len(kv) == 2:
#                     reqdict[kv[0].strip()] = kv[1].strip()
#
#         print 'Receive rquest :', reqdict
#         self.echo = socket_out
#         self.handle(reqdict)
#         socket_out.write(gvars.EOFSTR + '\n')
#         socket_out.flush()
#         socket_in.close()
#         socket_out.close()
#         pass
#
#     def handle_request_side(self, reqdict, address_tuple):
#         return sendrequest(address_tuple, reqdict)




# def extract_param(reqdict, param_des):
#     """Extract parameters from request dict
#
#     :param reqdict:  raw request k-v dict
#     :param param_des: params discription tuple, as (('param1_name', 1), ('param2_name', 0), )
#     :return params_dict: validated params dict
#     :raise ValueError: some parameter is not setted in reqdict
#     """
#     rtn_dict = {}
#     for name, nf in param_des:
#         value = reqdict.get(name)
#         if not value and nf == 1:
#             raise ValueError()
#         elif not value and nf == 0:
#             pass
#         else:
#             rtn_dict[name] = value
#     return rtn_dict


# def sendrequest(address, request_dict):
#     """Send Request to remote host
#
#     :param address:  tuple(ip_str, port_int)   remote host address
#     :param request_dict:    request parameter's dict
#     :return:  the module handler' output content (self.echo.write())
#     """
#     s = socket(AF_INET, SOCK_STREAM)
#     s.connect(address)
#     content = 'module='+request_dict['module'] + '\n'
#     for key, val in request_dict.items():
#         content += key + '=' + val + '\n'
#     content += '\n' + gvars.EOFSTR + '\n'
#     s.send(content)
#     rstr = ''
#     while True:
#         buf = s.recv(1024)
#         if not buf:
#             break
#         rstr += bytes(buf)
#         if rstr.endswith(gvars.EOFSTR):
#             break
#     s.close()
#     return rstr


